package team.bluepen.order.util;

import team.bluepen.order.data.entity.User;
import team.bluepen.order.constant.ErrorCode;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Kai
 */
public class UserChecker {
    public static final String USERNAME_REGEX = "^[a-zA-Z]\\w{3,18}$";
    public static final String PASSWORD_REGEX = "^[A-Za-z\\d._~!@#$^&*]{3,20}$";


    /**
     * 检查用户名和密码是否合规
     *
     * @param user 用户
     * @return {@link ErrorCode}
     */
    public static ErrorCode checkUser(User user) {
        if (!checkUsername(user.getUsername())) {
            return ErrorCode.ERROR_USERNAME_NON_COMPLIANCE;
        }
        if (!checkPassword(user.getPassword())) {
            return ErrorCode.ERROR_PASSWORD_NON_COMPLIANCE;
        }
        return ErrorCode.SUCCESS;
    }

    /**
     * 检查用户名是否合规<br>
     * 用户名规范：
     * <br>
     * <ul>
     *     <li>允许数字、字母及下划线</li>
     *     <li>最短3位，最长20位</li>
     *     <li>禁止除下划线外的特殊字符</li>
     * </ul>
     *
     * @param username 用户名
     * @return 是否合规
     */
    public static boolean checkUsername(String username) {
        if (username.length() > 20 || username.length() < 3) {
            return false;
        }
        Pattern pattern = Pattern.compile(USERNAME_REGEX);
        Matcher matcher = pattern.matcher(username);
        return matcher.matches();
    }

    /**
     * 检查密码是否合规<br>
     * 密码规范：<br>
     * <ul>
     *     <li>允许数字、字母及部分特殊字符</li>
     *     <li>最短3位，最长18位</li>
     * </ul>
     *
     * @param password 密码
     * @return 是否合规
     */
    public static boolean checkPassword(String password) {
        if (password.length() > 18 || password.length() < 3) {
            return false;
        }

        Pattern pattern = Pattern.compile(PASSWORD_REGEX);
        Matcher matcher = pattern.matcher(password);
        return matcher.matches();
    }
}
